package com.ruoyi.customer.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.common.DisCustomerRequestBo;
import com.ruoyi.customer.domain.Remark;
import com.ruoyi.customer.domain.bo.CustomerBo;
import com.ruoyi.customer.domain.bo.CustomerPoolPullBo;
import com.ruoyi.customer.domain.bo.CustomerReturnPoolBo;
import com.ruoyi.customer.domain.bo.RecordBo;
import com.ruoyi.customer.domain.vo.CustomerVo;
import com.ruoyi.customer.domain.vo.MxInfoVo;
import com.ruoyi.customer.mapper.RemarkMapper;
import com.ruoyi.customer.service.ICustomerService;
import com.ruoyi.disCustomer.domain.TCustomerDisRecord;
import com.ruoyi.disCustomer.domain.vo.TCustomerDisRecordVo;
import com.ruoyi.disCustomer.mapper.TCustomerDisRecordMapper;
import com.ruoyi.enums.BusTypeEnum;

import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import com.ruoyi.returnCustomer.domain.TCustomerReturnRecord;
import com.ruoyi.returnCustomer.domain.vo.TCustomerReturnRecordVo;
import com.ruoyi.returnCustomer.mapper.TCustomerReturnRecordMapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 客户信息
 *
 * @author suntf
 * @date 2023-07-29
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/customer")
public class CustomerController extends BaseController {

    private final ICustomerService iCustomerService;

    private final RemarkMapper remarkMapper;

    private final TCustomerDisRecordMapper disRecordMapper;

    private final TCustomerReturnRecordMapper recordMapper;


    /**
     * 查询客户信息列表
     */
    @GetMapping("/list")
    public TableDataInfo<CustomerVo> list(CustomerBo bo, PageQuery pageQuery) {
        //iCustomerService.sendStarCustomerToUser();
        return iCustomerService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出客户信息列表
     */
    @SaCheckPermission("customer:myCustomer:export")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CustomerBo bo, HttpServletResponse response) {
        List<CustomerVo> list = iCustomerService.queryList(bo);
        ExcelUtil.exportExcel(list, "客户信息", CustomerVo.class, response);
    }

    @GetMapping("/record/{id}")
    public R<List<Remark>> getRecordList(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        // 直接取数据库数据
        LambdaQueryWrapper<Remark> remarkLambda = new LambdaQueryWrapper<>();
        remarkLambda.eq(Remark::getCustomerId, id);
        remarkLambda.eq(Remark::getDelFlag, "0");
        remarkLambda.orderByDesc(BaseEntity::getCreateTime);
        List<Remark> remarks = remarkMapper.selectList(remarkLambda);
        if (!CollectionUtils.isEmpty(remarks)) {
            return R.ok(remarks);
        }
        return R.ok(Lists.newArrayList());
    }

    /**
     * 获取客户信息详细信息
     *
     * @param id 主键
     */
    //@SaCheckPermission("customer:myCustomer:query")
    @GetMapping("/{id}")
    public R<CustomerVo> getInfo(@NotNull(message = "主键不能为空")
    @PathVariable Long id) {
        // 流程记录放到备注当中展示
        CustomerVo customerVo = Optional.ofNullable(iCustomerService.queryById(id))
                .orElseThrow(() -> new BaseException("信息没有找到"));
        customerVo.setRemark(customerVo.getBz());
        customerVo.setBz("");
        return R.ok(customerVo);
    }

    /**
     * 新增客户信息
     */
    @SaCheckPermission("customer:myCustomer:add")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CustomerBo bo) {
        return toAjax(iCustomerService.insertByBo(bo));
    }

    /**
     * 修改客户信息
     */
    // @SaCheckPermission("customer:myCustomer:edit")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CustomerBo bo) {
        return toAjax(iCustomerService.updateByBo(bo));
    }

    /**
     * 删除客户信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("customer:myCustomer:remove")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
    @PathVariable Long[] ids) {
        return toAjax(iCustomerService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 我的客户退回
     *
     * @param customerReturnPoolBo
     * @return
     */
    @PostMapping("/customerReturnPool")
    @RepeatSubmit
    public R<Void> customerReturnPool(@RequestBody CustomerReturnPoolBo customerReturnPoolBo) {
        return toAjax(iCustomerService.customerReturnPool(customerReturnPoolBo));
    }


    /**
     * 我的客户拉取上级客户
     *
     * @param customerPoolPullBo
     * @return
     */
    @PostMapping("/customerPoolPull")
    @RepeatSubmit
    public R<Map<String, String>> customerPoolPull(@RequestBody CustomerPoolPullBo customerPoolPullBo) {
        Map<String, String> map = new HashMap<>();
        map.put("info", iCustomerService.customerPoolPull(customerPoolPullBo));
        return R.ok(map);
    }

    /**
     * 客户确认
     */
    @GetMapping("/customerRL/{ids}")
    @RepeatSubmit
    public R<Map<String, String>> customerRL(@PathVariable("ids") Long[] ids) {
        Map<String, String> map = new HashMap<>();
        map.put("info", iCustomerService.customerRL(ids));
        return R.ok(map);
    }

    @PostMapping("/saveBz")
    @RepeatSubmit
    public R<Void> saveBz(@RequestBody RecordBo recordBo) {
        iCustomerService.saveBz(recordBo);
        return R.ok();
    }

    /**
     * 获取明细信息
     *
     * @return
     */
    @GetMapping("/getMxInfo/{id}")
    public R<MxInfoVo> getMxInfo(@PathVariable("id") Long id) {
        MxInfoVo mxInfo = iCustomerService.getMxInfo(id);
        return R.ok(mxInfo);
    }

    /**
     * 设置vip，1 增加vip 0 减少vip
     *
     * @param type
     * @return com.ruoyi.common.core.domain.R
     * @author: suntf
     * @date: 2023/8/20 09:39
     */
    @GetMapping("setVip/{customerId}/{type}")
    public R setVip(@PathVariable("customerId") Long customerId, @PathVariable("type") int type) {
        return iCustomerService.setVip(customerId, type);
    }

    /**
     * 根据类型查询提醒信息
     *
     * @param type type team 团队 person 个人
     * @return com.ruoyi.common.core.domain.R
     * @author: suntf
     * @date: 2023/8/20 12:10
     */
    @GetMapping("getCustomerStar/{type}")
    public R getCustomerStar(@PathVariable("type") String type) {
        return R.ok(iCustomerService.getCustomerStar(type));
    }

    /**
     * 邀约
     *
     * @param customerId
     * @return
     */
    @GetMapping("/invite/{customerId}")
    public R invite(@PathVariable("customerId") Long customerId) {
        return iCustomerService.invite(customerId);
    }

    /**
     * 上门
     *
     * @param customerId
     * @return
     */
    @GetMapping("/upDoor/{customerId}")
    public R upDoor(@PathVariable("customerId") Long customerId) {
        return iCustomerService.upDoor(customerId);
    }

    /**
     * 下推客户
     *
     * @param customerId
     * @return
     */
    @GetMapping("/pushCustomer/{customerId}")
    public R pushCustomer(@PathVariable("customerId") Long[] customerId) {
        return iCustomerService.pushCustomer(customerId);
    }

    /**
     * 下推客户记录查看
     *
     * @param customerId
     * @return
     */
    @GetMapping("/pushCustomer/record/{customerId}")
    public R pushCustomerRecord(@PathVariable("customerId") Long customerId) {
        LambdaQueryWrapper<TCustomerDisRecord> query = new LambdaQueryWrapper<>();
        query.eq(TCustomerDisRecord::getCustomerId, customerId);
        //query.in(TCustomerDisRecord::getBusType, BusTypeEnum.PUSH.getCode(), BusTypeEnum.PUSH_FP.getCode(), BusTypeEnum.PUSH_RETURN.getCode());
        query.orderByDesc(BaseEntity::getCreateTime);
        List<TCustomerDisRecordVo> tCustomerDisRecordVos = disRecordMapper.selectVoList(query);
        if (!CollectionUtils.isEmpty(tCustomerDisRecordVos)) {
            return R.ok(tCustomerDisRecordVos);
        }
        return R.ok(Lists.newArrayList());
    }


    /**
     * 退回客户记录查看
     *
     * @param customerId
     * @return
     */
    @GetMapping("/returnCustomer/record/{customerId}")
    public R returnCustomer(@PathVariable("customerId") Long customerId) {
        LambdaQueryWrapper<TCustomerReturnRecord> query = new LambdaQueryWrapper<>();
        query.eq(TCustomerReturnRecord::getCustomerId, customerId);
        query.orderByDesc(BaseEntity::getCreateTime);
        List<TCustomerReturnRecordVo> returnRecordVos = recordMapper.selectVoList(query);
        if (!CollectionUtils.isEmpty(returnRecordVos)) {
            return R.ok(returnRecordVos);
        }
        return R.ok(Lists.newArrayList());
    }


    @PostMapping("/pushCustomer/pusDis")
    public R pushDis(@RequestBody DisCustomerRequestBo requestBo) {
        iCustomerService.pushDis(requestBo);
        return R.ok();
    }

    @PostMapping("/pushCustomer/return")
    public R pushDis(@RequestBody CustomerReturnPoolBo pushDisBo) {
        iCustomerService.pushReturn(pushDisBo);
        return R.ok();
    }


}
